<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { categoryApi } from '../api'

const router = useRouter()

// 成功消息
const successMsg = ref('')

// 分类列表数据
const categories = ref([])
// 分页信息
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
  pages: 0
})
// 加载状态
const loading = ref(false)
// 错误信息
const errorMsg = ref('')
// 显示添加分类模态框
const showAddModal = ref(false)
// 显示编辑分类模态框
const showEditModal = ref(false)
// 当前编辑的分类
const currentCategory = ref(null)

// 表单数据
const formData = ref({
  name: '',
  description: '',
  icon: '📱',
  color: '#3b82f6',
  sort: 0,
  status: 1
})

// 可选图标
const iconOptions = ['📱', '🌐', '📧', '📞', '🏠', '🏢', '🛒', '💳', '🎵', '📷', '📝', '🔗']

// 可选颜色
const colorOptions = [
  '#3b82f6', '#ef4444', '#10b981', '#f59e0b',
  '#8b5cf6', '#ec4899', '#06b6d4', '#84cc16'
]

// 获取分类列表
const fetchCategories = async (page = 1) => {
  loading.value = true
  errorMsg.value = ''
  successMsg.value = ''
  
  try {
    const response = await categoryApi.getCategories()
    if (response && response.data) {
      if (Array.isArray(response.data)) {
        // 如果直接返回数组
        categories.value = response.data
        pagination.value = {
          current: page,
          size: 10,
          total: response.data.length,
          pages: Math.ceil(response.data.length / 10)
        }
      } else {
        // 如果返回分页对象
        categories.value = response.data.list || response.data.records || []
        pagination.value = {
          current: response.data.current || page,
          size: response.data.size || 10,
          total: response.data.total || 0,
          pages: response.data.pages || 1
        }
      }
    } else {
      categories.value = []
    }
  } catch (error) {
    errorMsg.value = '获取分类列表失败: ' + (error.message || '未知错误')
    console.error('获取分类列表失败:', error)
    categories.value = []
  } finally {
    loading.value = false
  }
}

// 打开添加分类模态框
const openAddModal = () => {
  formData.value = {
    name: '',
    description: '',
    icon: '📱',
    color: '#3b82f6',
    sort: 0,
    status: 1
  }
  showAddModal.value = true
}

// 打开编辑分类模态框
const openEditModal = (category) => {
  currentCategory.value = category
  formData.value = { ...category }
  showEditModal.value = true
}

// 关闭模态框
const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  currentCategory.value = null
}

// 保存分类
const saveCategory = async () => {
  try {
    errorMsg.value = ''
    successMsg.value = ''
    
    if (showEditModal.value) {
      // 更新分类
      await categoryApi.updateCategory(formData.value)
      successMsg.value = '分类更新成功！'
    } else {
      // 添加分类
      await categoryApi.createCategory(formData.value)
      successMsg.value = '分类创建成功！'
    }
    
    closeModal()
    // 重新获取分类列表
    await fetchCategories()
    
    // 3秒后清除成功消息
    setTimeout(() => {
      successMsg.value = ''
    }, 3000)
  } catch (error) {
    errorMsg.value = '保存分类失败: ' + (error.message || '未知错误')
  }
}

// 删除分类
const deleteCategory = async (id) => {
  if (!confirm('确定要删除这个分类吗？此操作不可恢复。')) {
    return
  }
  
  try {
    errorMsg.value = ''
    successMsg.value = ''
    
    await categoryApi.deleteCategory(id)
    successMsg.value = '分类删除成功！'
    
    // 重新获取分类列表
    await fetchCategories()
    
    // 3秒后清除成功消息
    setTimeout(() => {
      successMsg.value = ''
    }, 3000)
  } catch (error) {
    errorMsg.value = '删除分类失败: ' + (error.message || '未知错误')
  }
}

// 切换分类状态
const toggleStatus = async (category) => {
  try {
    errorMsg.value = ''
    successMsg.value = ''
    
    const updatedCategory = {
      ...category,
      status: category.status === 1 ? 0 : 1
    }
    
    await categoryApi.updateCategory(updatedCategory)
    successMsg.value = `分类状态${updatedCategory.status === 1 ? '启用' : '禁用'}成功！`
    
    // 重新获取分类列表
    await fetchCategories()
    
    // 3秒后清除成功消息
    setTimeout(() => {
      successMsg.value = ''
    }, 3000)
  } catch (error) {
    errorMsg.value = '更新状态失败: ' + (error.message || '未知错误')
  }
}

// 处理分页变化
const handlePageChange = (page) => {
  fetchCategories(page)
}

// 组件挂载时获取分类列表
onMounted(() => {
  fetchCategories()
})
</script>

<template>
  <div class="category-management">
    <div class="page-header">
      <h2>分类管理</h2>
      <button @click="openAddModal" class="add-btn">添加分类</button>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMsg" class="error-message">
      {{ errorMsg }}
    </div>
    
    <!-- 成功提示 -->
    <div v-if="successMsg" class="success-message">
      {{ successMsg }}
    </div>
    
    <!-- 加载中 -->
    <div v-if="loading" class="loading-spinner">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 分类列表 -->
    <div v-else-if="categories.length > 0" class="category-list">
      <div class="category-grid">
        <div v-for="category in categories" :key="category.id" class="category-card">
          <div class="category-header">
            <div class="category-icon" :style="{ backgroundColor: category.color }">
              {{ category.icon }}
            </div>
            <div class="category-info">
              <h3 class="category-name">{{ category.name }}</h3>
              <p class="category-description">{{ category.description }}</p>
            </div>
            <div class="category-status">
              <span 
                :class="['status-badge', category.status === 1 ? 'active' : 'inactive']"
                @click="toggleStatus(category)"
              >
                {{ category.status === 1 ? '启用' : '禁用' }}
              </span>
            </div>
          </div>
          
          <div class="category-meta">
            <span class="sort-order">排序: {{ category.sort }}</span>
            <span class="create-time">创建于: {{ new Date(category.createTime).toLocaleDateString() }}</span>
          </div>
          
          <div class="category-actions">
            <button @click="openEditModal(category)" class="edit-btn">编辑</button>
            <button @click="deleteCategory(category.id)" class="delete-btn">删除</button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="pagination.pages > 1" class="pagination">
        <button 
          :disabled="pagination.current === 1" 
          @click="handlePageChange(pagination.current - 1)" 
          class="page-btn"
        >
          上一页
        </button>
        
        <span class="page-info">
          {{ pagination.current }} / {{ pagination.pages }}
        </span>
        
        <button 
          :disabled="pagination.current === pagination.pages" 
          @click="handlePageChange(pagination.current + 1)" 
          class="page-btn"
        >
          下一页
        </button>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      <p>还没有任何分类</p>
      <button @click="openAddModal" class="add-btn">创建第一个分类</button>
    </div>
    
    <!-- 添加分类模态框 -->
    <div v-if="showAddModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>添加分类</h3>
          <button @click="closeModal" class="close-btn">×</button>
        </div>
        
        <form @submit.prevent="saveCategory" class="category-form">
          <div class="form-group">
            <label>分类名称</label>
            <input v-model="formData.name" type="text" placeholder="请输入分类名称" required>
          </div>
          
          <div class="form-group">
            <label>分类描述</label>
            <textarea v-model="formData.description" placeholder="请输入分类描述" rows="3"></textarea>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>图标</label>
              <div class="icon-selector">
                <div 
                  v-for="icon in iconOptions" 
                  :key="icon"
                  :class="['icon-option', { active: formData.icon === icon }]"
                  @click="formData.icon = icon"
                >
                  {{ icon }}
                </div>
              </div>
            </div>
            
            <div class="form-group">
              <label>颜色</label>
              <div class="color-selector">
                <div 
                  v-for="color in colorOptions" 
                  :key="color"
                  :class="['color-option', { active: formData.color === color }]"
                  :style="{ backgroundColor: color }"
                  @click="formData.color = color"
                ></div>
              </div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>排序</label>
              <input v-model.number="formData.sort" type="number" min="0" placeholder="排序值">
            </div>
            
            <div class="form-group">
              <label>状态</label>
              <select v-model="formData.status">
                <option :value="1">启用</option>
                <option :value="0">禁用</option>
              </select>
            </div>
          </div>
          
          <div class="form-actions">
            <button type="button" @click="closeModal" class="cancel-btn">取消</button>
            <button type="submit" class="save-btn">保存</button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 编辑分类模态框 -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>编辑分类</h3>
          <button @click="closeModal" class="close-btn">×</button>
        </div>
        
        <form @submit.prevent="saveCategory" class="category-form">
          <div class="form-group">
            <label>分类名称</label>
            <input v-model="formData.name" type="text" placeholder="请输入分类名称" required>
          </div>
          
          <div class="form-group">
            <label>分类描述</label>
            <textarea v-model="formData.description" placeholder="请输入分类描述" rows="3"></textarea>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>图标</label>
              <div class="icon-selector">
                <div 
                  v-for="icon in iconOptions" 
                  :key="icon"
                  :class="['icon-option', { active: formData.icon === icon }]"
                  @click="formData.icon = icon"
                >
                  {{ icon }}
                </div>
              </div>
            </div>
            
            <div class="form-group">
              <label>颜色</label>
              <div class="color-selector">
                <div 
                  v-for="color in colorOptions" 
                  :key="color"
                  :class="['color-option', { active: formData.color === color }]"
                  :style="{ backgroundColor: color }"
                  @click="formData.color = color"
                ></div>
              </div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>排序</label>
              <input v-model.number="formData.sort" type="number" min="0" placeholder="排序值">
            </div>
            
            <div class="form-group">
              <label>状态</label>
              <select v-model="formData.status">
                <option :value="1">启用</option>
                <option :value="0">禁用</option>
              </select>
            </div>
          </div>
          
          <div class="form-actions">
            <button type="button" @click="closeModal" class="cancel-btn">取消</button>
            <button type="submit" class="save-btn">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.category-management {
  background: var(--card-bg);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-lg);
  padding: var(--spacing-xl);
  margin: var(--spacing-md);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 2px solid var(--border-color);
  position: relative;
}

.page-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 80px;
  height: 2px;
  background: var(--gradient-primary);
  border-radius: 1px;
}

h2 {
  margin: 0;
  color: var(--dark-color);
  font-weight: 700;
  font-size: 1.8rem;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.add-btn {
  background: var(--gradient-primary);
  color: white;
  border: none;
  padding: var(--spacing-sm) var(--spacing-lg);
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-weight: 600;
  font-size: 0.9rem;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-md);
  position: relative;
  overflow: hidden;
}

.add-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
  transition: left 0.5s;
}

.add-btn:hover::before {
  left: 100%;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.error-message {
  background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
  color: var(--danger-color);
  padding: var(--spacing-md);
  border-radius: var(--border-radius-md);
  margin-bottom: var(--spacing-lg);
  border-left: 4px solid var(--danger-color);
  box-shadow: var(--shadow-sm);
  font-weight: 500;
}

.success-message {
  background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
  color: #2e7d32;
  padding: var(--spacing-md);
  border-radius: var(--border-radius-md);
  margin-bottom: var(--spacing-lg);
  border-left: 4px solid #4caf50;
  box-shadow: var(--shadow-sm);
  font-weight: 500;
  animation: slideInDown 0.3s ease-out;
}

@keyframes slideInDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xxl) 0;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(var(--primary-rgb), 0.1);
  border-radius: 50%;
  border-top-color: var(--primary-color);
  animation: spin 1s ease-in-out infinite;
  margin-bottom: var(--spacing-md);
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-spinner p {
  color: var(--text-secondary);
  font-weight: 500;
  margin: 0;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: var(--spacing-xl);
  margin-bottom: var(--spacing-xl);
}

.category-card {
  background: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-lg);
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-md);
  position: relative;
}

.category-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: var(--gradient-primary);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.category-card:hover {
  transform: translateY(-8px);
  box-shadow: var(--shadow-xl);
}

.category-card:hover::before {
  transform: scaleX(1);
}

.category-header {
  display: flex;
  align-items: center;
  padding: var(--spacing-lg);
  gap: var(--spacing-md);
}

.category-icon {
  width: 50px;
  height: 50px;
  border-radius: var(--border-radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: white;
  box-shadow: var(--shadow-sm);
}

.category-info {
  flex: 1;
}

.category-name {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: 1.2rem;
  color: var(--dark-color);
  font-weight: 600;
}

.category-description {
  margin: 0;
  font-size: 0.9rem;
  color: var(--text-secondary);
  line-height: 1.4;
}

.category-status {
  display: flex;
  align-items: center;
}

.status-badge {
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--border-radius-sm);
  font-size: 0.8rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.status-badge.active {
  background: var(--success-light);
  color: var(--success-color);
}

.status-badge.inactive {
  background: var(--danger-light);
  color: var(--danger-color);
}

.category-meta {
  display: flex;
  justify-content: space-between;
  padding: 0 var(--spacing-lg);
  margin-bottom: var(--spacing-md);
  font-size: 0.8rem;
  color: var(--text-muted);
}

.category-actions {
  display: flex;
  gap: var(--spacing-sm);
  padding: var(--spacing-md) var(--spacing-lg);
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-top: 1px solid var(--border-color);
}

.edit-btn, .delete-btn {
  flex: 1;
  padding: var(--spacing-sm) var(--spacing-md);
  border: none;
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-size: 0.9rem;
  font-weight: 600;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.edit-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  box-shadow: var(--shadow-sm);
}

.edit-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.delete-btn {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: white;
  box-shadow: var(--shadow-sm);
}

.delete-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: var(--spacing-xxl);
  gap: var(--spacing-md);
}

.page-btn {
  padding: var(--spacing-sm) var(--spacing-lg);
  border: 2px solid var(--border-color);
  background: var(--card-bg);
  color: var(--dark-color);
  cursor: pointer;
  border-radius: var(--border-radius-md);
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-sm);
}

.page-btn:hover:not(:disabled) {
  color: white;
  border-color: var(--primary-color);
  background: var(--primary-color);
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.page-info {
  margin: 0;
  color: var(--text-secondary);
  font-weight: 600;
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--bg-light);
  border-radius: var(--border-radius-md);
  border: 2px solid var(--border-color);
}

.empty-state {
  text-align: center;
  padding: var(--spacing-xxl) 0;
  color: var(--text-secondary);
}

.empty-state p {
  margin-bottom: var(--spacing-xl);
  font-size: 1.1rem;
  font-weight: 500;
}

.empty-state::before {
  content: '📂';
  font-size: 4rem;
  display: block;
  margin-bottom: var(--spacing-lg);
  opacity: 0.5;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: rgba(255, 255, 255, 0.98);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-xl);
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-lg) var(--spacing-xl);
  border-bottom: 1px solid var(--border-color);
}

.modal-header h3 {
  margin: 0;
  color: var(--dark-color);
  font-weight: 700;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: var(--text-secondary);
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: var(--danger-light);
  color: var(--danger-color);
}

.category-form {
  padding: var(--spacing-xl);
}

.form-group {
  margin-bottom: var(--spacing-lg);
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-lg);
}

.form-group label {
  display: block;
  margin-bottom: var(--spacing-sm);
  font-weight: 600;
  color: var(--dark-color);
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: var(--spacing-md);
  border: 2px solid var(--border-color);
  border-radius: var(--border-radius-md);
  font-size: 1rem;
  font-family: var(--font-family);
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.95);
  color: var(--dark-color);
  box-sizing: border-box;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  border-color: var(--primary-color);
  outline: none;
  box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.1);
  background: white;
}

.icon-selector {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: var(--spacing-sm);
}

.icon-option {
  width: 40px;
  height: 40px;
  border: 2px solid var(--border-color);
  border-radius: var(--border-radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.9);
}

.icon-option:hover {
  border-color: var(--primary-color);
  transform: scale(1.1);
}

.icon-option.active {
  border-color: var(--primary-color);
  background: var(--primary-light);
  transform: scale(1.1);
}

.color-selector {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: var(--spacing-sm);
}

.color-option {
  width: 40px;
  height: 40px;
  border: 3px solid transparent;
  border-radius: var(--border-radius-md);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.color-option:hover {
  transform: scale(1.1);
  box-shadow: var(--shadow-md);
}

.color-option.active {
  border-color: var(--dark-color);
  transform: scale(1.1);
  box-shadow: var(--shadow-lg);
}

.color-option.active::after {
  content: '✓';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-weight: bold;
  text-shadow: 0 1px 2px rgba(0,0,0,0.5);
}

.form-actions {
  display: flex;
  gap: var(--spacing-md);
  justify-content: flex-end;
  margin-top: var(--spacing-xl);
  padding-top: var(--spacing-lg);
  border-top: 1px solid var(--border-color);
}

.cancel-btn {
  background: var(--bg-light);
  color: var(--text-secondary);
  border: 2px solid var(--border-color);
  padding: var(--spacing-sm) var(--spacing-lg);
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: var(--danger-light);
  color: var(--danger-color);
  border-color: var(--danger-color);
}

.save-btn {
  background: var(--gradient-primary);
  color: white;
  border: none;
  padding: var(--spacing-sm) var(--spacing-lg);
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-md);
}

.save-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}
</style>